package cn.chenc.framework.core.manage;


import cn.chenc.framework.core.util.Threads;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @author secret
 */
public class AsyncManager
{
    /**
     * 默认操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor;

    public AsyncManager() {

    }

    public AsyncManager(ScheduledExecutorService executor) {
        this.executor = executor;
    }

    public ScheduledExecutorService getExecutor() {
        return executor;
    }

    public void setExecutor(ScheduledExecutorService executor) {
        this.executor = executor;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void executeDelay(TimerTask task)
    {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    public void executeDalay(TimerTask task,long delay,TimeUnit timeUnit) {
        executor.schedule(task, delay, timeUnit);
    }


    public void execute(TimerTask task)
    {
        executor.schedule(task, 0, TimeUnit.MILLISECONDS);
    }


    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        Threads.shutdownAndAwaitTermination(executor);
    }
}
